package com.example.server.controller;
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.example.common.exception.YebException;
import com.example.common.pojo.*;
import com.example.server.service.*;
import com.example.common.vo.RespBean;
import com.example.common.vo.RespPageBean;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 小红
 * @since 2022-09-02
 */
@RestController
@RequestMapping("/employee/basic")
public class EmployeeController {

//    @Autowired
//    private IEmployeeEcService employeeEcService;
    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private INationService nationService;

    @Autowired
    private IDepartmentService departmentService;

    @Autowired
    private IPoliticsStatusService politicsStatusService;

    @Autowired
    private IJoblevelService iJoblevelService;

    @Autowired
    private IPositionService iPositionService;
    @GetMapping("/")
    public RespPageBean list(@RequestParam(defaultValue = "1") Integer currentPage,
                             @RequestParam(defaultValue = "10")Integer size,
                             Employee employee){
        return employeeService.getAll(currentPage,size,employee);
    }
    @ApiOperation("获取所有政治面貌")
    @GetMapping("/politicsstatus")
    public List<PoliticsStatus> getAllPolitics(){
        return politicsStatusService.list();
    }
    @GetMapping("/nations")
    public List<Nation> nationList(){
        return nationService.list();
    }

    @GetMapping("/deps")
    public List<Department> departmentList(){
        return departmentService.getDeptLevel();
    }

    @GetMapping("/joblevels")
    public List<Joblevel> joblevelList(){
        return iJoblevelService.list();
    }

    @GetMapping("/positions")
    public List<Position> positionList(){
        return iPositionService.list();
    }

    @GetMapping("/maxWorkID")
    public RespBean maxWorkID(){
        return employeeService.maxWorkId();
    }

    @PostMapping("/")
    public RespBean addEmp(@RequestBody Employee employee){
        return employeeService.addEmp(employee);
    }

    @PutMapping("/")
    public RespBean editEmp (@RequestBody Employee employee){
        employeeService.updateById(employee);
        return RespBean.success();
    }

    @DeleteMapping("/{id}")
    public RespBean deleteById(@PathVariable Integer id){
        employeeService.removeById(id);
        return RespBean.success();
    }

    @GetMapping("/export")
    public void exportExcel(HttpServletResponse response){
        /**
         * 1.查询要输出的数据
         * 2.EasyPoi的规则，生成要输出的文件
         * 3.通过response输出文件
         */

        List<Employee> list = employeeService.getAllSimper();
        ExportParams exportParams = new ExportParams("员工表", "员工表", ExcelType.HSSF);
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, Employee.class, list);
        ServletOutputStream outputStream = null;
        try {
            response.setHeader("content-type", "application/octet-stream");
            response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode("员工表.xls"));
            outputStream = response.getOutputStream();
            workbook.write(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @PostMapping("/import")
    public RespBean importEmployee(MultipartFile file){
        ///base4 -> json 传递文件
        /**
         * 1.导入参数设置
         * 2.查询所有的中间表
         * 3.进行解析上传的文件 - List<Employee>
         * 4.每一个Employee对象都缺少关联表外键
         */
        ImportParams importParams = new ImportParams();
        importParams.setHeadRows(1);
        List<Nation> nations = nationService.list();
        List<Department> departments = departmentService.list();
        List<Joblevel> joblevels = iJoblevelService.list();

        try{
            List<Employee>  employeeList= ExcelImportUtil.importExcel(file.getInputStream(), Employee.class, importParams);
            employeeList.forEach(employee -> {
                Nation nation = employee.getNation();
                int i = nations.indexOf(nation);
                Nation targetNation = nations.get(i);

                Department department = employee.getDepartment();
                int i1 = departments.indexOf(department);
                Department targetDepartment = departments.get(i1);

                Joblevel joblevel = employee.getJoblevel();
                int i2 = joblevels.indexOf(joblevel);
                Joblevel targetJoblevel = joblevels.get(i2);

                if (targetNation != null) {
                    employee.setNationId(targetNation.getId());
                }
                if (targetDepartment != null) {
                    employee.setDepartmentId(targetDepartment.getId());
                }
                if (targetJoblevel != null) {
                    employee.setJobLevelId(targetJoblevel.getId());
                }
            });
            boolean result = employeeService.saveBatch(employeeList);
            return RespBean.success("导入成功",null);
        }catch (Exception e){
            YebException yebException = new YebException(505,"导入员工失败" + e.getMessage());
            yebException.setStackTrace(e.getStackTrace());
            throw yebException;
        }
    }
}
